package com.longshine.arthmetic.pattern.product_custom;
/**
 * 三个线程同时打印 一次
* @ClassName: ThreeThreadsSync 
* @Description: 
* @author yitian.cao
* @date 2013-10-31 下午02:24:39 
*
 */
public class ThreeThreadsSync {

	private Object lock1 = new Object();
	private Object lock2 = new Object();
	private Object lock3 = new Object();
	
	public void work() throws Exception{
		new SubThread("A",lock1,lock3).start();
		Thread.sleep(10);//让A线程执行完全
		new SubThread("B",lock2,lock1).start();
		Thread.sleep(10);
		new SubThread("C",lock3,lock2).start();
		Thread.sleep(10);
	}
	
	class SubThread extends Thread{
		int a = 10;
		String name;
		Object self;
		Object prev;
		public SubThread(String name,Object self,Object prev){
			this.name = name;
			this.self = self;
			this.prev = prev;
		}
		public void run(){
			while(a-- >0){
				synchronized(prev){
					synchronized(self){
						System.out.print(name);
						try {
							Thread.sleep(1);//进入主线程
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						//通知下一个线程运行
						self.notify();
					}
					try {
						prev.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	public static void main(String[] args) throws Exception{
		new ThreeThreadsSync().work();
	}
}
